using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{
	
	public partial class FormMasterEdit : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		
#region Design Data Bind Methond
		
		//Bind the Design Time Form controls
		private void BindDesignForm()
		{
			
			if (objFormInfo == null)
			{
				objFormInfo = new Code5Systems.FormMaster.Business.FormInfo();
				ViewState.Add("NewForm", "True");
			}
			
			if (!Page.IsPostBack)
			{
				for (int i = 1; i <= 200; i++)
				{
					this.lstTableRows.Items.Add(i.ToString());
				}
				
				for (int i = 1; i <= 15; i++)
				{
					this.lstTableColumns.Items.Add(i.ToString());
				}
			}
			
			this.lstTableColumns.SelectedIndex = this.lstTableColumns.Items.IndexOf(this.lstTableColumns.Items.FindByValue(objFormInfo.CurrentPage.TableColumnsText));
			this.lstTableRows.SelectedIndex = this.lstTableRows.Items.IndexOf(this.lstTableRows.Items.FindByValue(objFormInfo.CurrentPage.TableRowsText));
			this.lstLabelPosition.SelectedIndex = this.lstLabelPosition.Items.IndexOf(this.lstLabelPosition.Items.FindByValue(objFormInfo.CurrentPage.LabelPositionText));
			
			objFormCtl.Pages.Sort((p1, p2) => p1.PageNum.CompareTo(p2.PageNum));
			this.lstFormPage.Items.Clear();
			this.lstFormPage.DataSource = objFormCtl.Pages;
			this.lstFormPage.DataBind();
			
			this.lstFormPage.Items.Add(new ListItem(Localization.GetString("NewPage", LocalResourceFile), "new"));
			this.lstFormPage.Items.Add(new ListItem(Localization.GetString("CopyPage", LocalResourceFile), "copy"));
			this.lstFormPage.Items.Add(new ListItem(Localization.GetString("DeletePage", LocalResourceFile), "delete"));
			
			this.lstFormPage.SelectedIndex = this.lstFormPage.Items.IndexOf(this.lstFormPage.Items.FindByValue(this.currentPage.Value));
			
			this.txtPageShortName.Text = objFormInfo.CurrentPage.ShortName;
			this.txtPageTitle.Text = objFormInfo.CurrentPage.Title;
			this.chkUseTitle.Checked = objFormInfo.CurrentPage.UseTitle;
			
			//CreateForm()
			//CreateMoveTo()
			
			this.pnlDesign.Visible = true;
			this.pnlField.Visible = false;
		}
		
		
		private void CreateMoveTo()
		{
			tblMoveTo.Rows.Clear();
			Table pageTable;
			TableRow row = default(TableRow);
			TableRow innerRow = default(TableRow);
			TableCell cell = default(TableCell);
			TableCell innerCell = default(TableCell);
			
			if (_previewMode)
			{
				return;
			}
			
			row = new TableRow();
			cell = new TableCell();
			cell.ColumnSpan = objFormInfo.CurrentPage.TableColumns;
			cell.HorizontalAlign = HorizontalAlign.Center;
			cell.Attributes.Add("style", "white-space:nowrap;");
			Label lblHeader = new Label();
			lblHeader.ID = "lblMoveCopyHeader";
			lblHeader.Font.Bold = true;
			lblHeader.Font.Size = FontUnit.Point(10);
			lblHeader.ForeColor = System.Drawing.Color.Black;
			lblHeader.Text = Localization.GetString("MoveCtlHeader", this.LocalResourceFile);
			cell.Controls.Add(lblHeader);
			row.Cells.Add(cell);
			tblMoveTo.Rows.Add(row);
			
			// Make an inner table on first row for "Pin" and "Cancel"
			Table innerTable = new Table();
			innerTable.Width = Unit.Percentage(100.0);
			innerTable.BorderStyle = BorderStyle.None;
			innerTable.CellPadding = 0;
			innerTable.CellSpacing = 0;

			// Pin Cell
			innerRow = new TableRow();
			innerRow.Attributes.Add("style", "border-bottom:1px solid black;");
			innerCell = new TableCell();
			innerCell.Attributes.Add("style", "border-right:1px solid black;");
			innerCell.Width = Unit.Percentage(50.0);
			innerCell.BorderStyle = BorderStyle.None;
			innerCell.HorizontalAlign = HorizontalAlign.Center;
			HyperLink pinLink = new HyperLink();
			pinLink.CssClass = "CommandButton";
			pinLink.TabIndex = (short) 1000;
			pinLink.Font.Bold = true;
			pinLink.EnableViewState = false;
			pinLink.Text = Localization.GetString("Pin", this.LocalResourceFile);
			pinLink.ID = "hlPin";
			pinLink.NavigateUrl = "#";
			innerCell.Controls.Add(pinLink);
			innerRow.Cells.Add(innerCell);

			// Cancel Cell
			innerCell = new TableCell();
			//innerCell.Attributes.Add("style", "width:50%;");
			innerCell.Width = Unit.Percentage(50.0);
			innerCell.BorderStyle = BorderStyle.None;
			innerCell.HorizontalAlign = HorizontalAlign.Center;
			LinkButton lbCancel = new LinkButton();
			lbCancel.Text = Localization.GetString("Cancel", this.LocalResourceFile);
			lbCancel.ID = "cmdCancelMove";
			lbCancel.CausesValidation = false;
			lbCancel.CssClass = "CommandButton";
			lbCancel.TabIndex = (short) 1000;
			lbCancel.Font.Bold = true;
			lbCancel.EnableViewState = false;
			innerCell.Controls.Add(lbCancel);
			innerRow.Cells.Add(innerCell);
			innerTable.Rows.Add(innerRow);

			// Page Cell
			innerRow = new TableRow();
			innerCell = new TableCell();
			//innerCell.Attributes.Add("style", "border-bottom:1px solid black;");
			//innerCell.Width = Unit.Percentage(33.0);
			innerCell.BorderStyle = BorderStyle.None;
			innerCell.ColumnSpan = 2;
			innerCell.HorizontalAlign = HorizontalAlign.Center;
			DropDownList lstPage = new DropDownList();
			lstPage.ID = "lstMoveToPage";
			lstPage.CssClass = "tinyDropdown";
			lstPage.Width = Unit.Pixel(60);
			foreach (var page in objFormCtl.Pages)
			{
				var item = new ListItem(page.ShortName, "page" + page.PageNum);
				if (objFormInfo.CurrentPage.PageNum == page.PageNum)
				{
					item.Selected = true;
				}
				lstPage.Items.Add(item);
			}

			Label lblPage = new Label();
			lblPage.Text = Localization.GetString("ToPage", this.LocalResourceFile);
			lblPage.CssClass = "tinylabel";
			lblPage.Font.Bold = true;
			innerCell.Controls.Add(lblPage);
			innerCell.Controls.Add(lstPage);
			innerRow.Cells.Add(innerCell);
			innerTable.Rows.Add(innerRow);

			// End Inner Table

			cell = new TableCell();
			cell.ColumnSpan = objFormInfo.CurrentPage.TableColumns;
			cell.Attributes.Add("style", "margin:0px;padding:0px;");
			cell.Controls.Add(innerTable);
			row = new TableRow();
			row.Cells.Add(cell);
			tblMoveTo.Rows.Add(row);

			Code5Systems.FormMaster.Business.CellInfo[,] pageAry;

			FormPageInfo curPage = objFormInfo.CurrentPage;

			foreach (var  page in this.objFormCtl.Pages)
			{
				pageTable = new Table();
				pageTable.CssClass = "C5SLLC_movetopage";
				pageTable.Width = Unit.Percentage(100.0);
				pageTable.BorderStyle = BorderStyle.None;
				pageTable.CellPadding = 0;
				pageTable.CellSpacing = 0;

				objFormInfo.CurrentPage = page;
				pageAry = this.objFormCtl.GetTableMatrix(objFormInfo, page.PageNum);

				for (int iRow = 1; iRow <= page.TableRows; iRow++)
				{
					row = new TableRow();
					if (iRow == page.TableRows)
					{
						row.BorderStyle = BorderStyle.None;
					}
					for (int iCol = 1; iCol <= page.TableColumns; iCol++)
					{
						cell = new TableCell();
						if (iCol == page.TableColumns)
						{
							cell.Attributes.Add("style", "border-right:none;");
						}
						
						if (page.TableColumns == 1)
						{
							cell.ColumnSpan = 2;
						}
						cell.Wrap = false;

						CellInfo oCellInfo = pageAry[iRow - 1, iCol - 1];

						if (!oCellInfo.IsSpanned)
						{
							if (oCellInfo.IsEmpty)
							{
								LinkButton lbMoveTo = default(LinkButton);
								lbMoveTo = new LinkButton();
								lbMoveTo.Text = "R:" + iRow.ToString() + "-C:" + iCol.ToString();
								lbMoveTo.ID = String.Format("cmdMoveToCell{0}_{1}_{2}", page.PageNum, iRow, iCol);
								lbMoveTo.CommandName = FormController.MoveDirection.MoveTo.ToString();
								lbMoveTo.CommandArgument = String.Format("{0},{1},{2}", page.PageNum, iRow, iCol);
								lbMoveTo.CausesValidation = false;
								lbMoveTo.CssClass = "CommandButton";
								lbMoveTo.ToolTip = String.Format(Localization.GetString("MoveCopyToolTip", this.LocalResourceFile), iRow, iCol);
								lbMoveTo.TabIndex = (short)1000;
								lbMoveTo.Font.Bold = false;
								lbMoveTo.Font.Size = FontUnit.XXSmall;
								lbMoveTo.EnableViewState = false;
								lbMoveTo.OnClientClick = "jQuery().HideMoveCopyTo();";
								lbMoveTo.Command += new System.Web.UI.WebControls.CommandEventHandler(cmdMove_Click);

								cell.Attributes.Add("onmouseover", " this.className=\'cellHoverON\'; ");
								cell.Attributes.Add("onmouseout", " this.className=\'cellHoverOFF\'; ");
								cell.CssClass = "cellHoverOFF";
								cell.Controls.Add(lbMoveTo);
							}
							else
							{
								cell.Text = "&#160;";
								if (!string.IsNullOrEmpty(this.hdnManagerLoc.Value))
								{
									ControlLoaction ctlLocation = new ControlLoaction(this.hdnManagerLoc.Value);
									if (oCellInfo.Row == ctlLocation.Row && oCellInfo.Col == ctlLocation.Col)
									{
										cell.CssClass = "MoveSource";
									}
								}
							}
						}
						row.Cells.Add(cell);
					}
					pageTable.Rows.Add(row);
				}

				cell = new TableCell();
				cell.BorderStyle = BorderStyle.None;
				cell.ColumnSpan = page.TableColumns;
				cell.Attributes.Add("style", "margin:0px;padding:0px;border-right:1px solid black;");
				cell.Controls.Add(pageTable);
				row = new TableRow();
				row.ID = "page" + page.PageNum;
				if (page.PageNum != curPage.PageNum)
				{
					row.Attributes.Add("style", "display:none;");
				}
				row.CssClass = "C5SLLC_movetablerow";
				row.Cells.Add(cell);
				tblMoveTo.Rows.Add(row); 
			}

			objFormInfo.CurrentPage = curPage;
		}

		private void CreateCalxWizard()
		{
			HtmlGenericControl fieldsContainerDiv = new HtmlGenericControl("div");
			HtmlGenericControl H5pageName;
			HtmlGenericControl ULpageFields;
			HtmlGenericControl LIpageField;
			string fieldLabel;
			HtmlGenericControl DivClear;
			CellInfo cellInfo = null;

			foreach (var page in this.objFormCtl.Pages)
			{
				H5pageName = new HtmlGenericControl("h5");
				H5pageName.InnerText = page.ShortName;
				fieldsContainerDiv.Controls.Add(H5pageName);
				ULpageFields = new HtmlGenericControl("ul");
				ULpageFields.Attributes.Add("class", "fields");
				tAry = this.objFormCtl.GetTableMatrix(objFormInfo, page.PageNum);

				for (int iCols = 1; iCols <= page.TableColumns; iCols++)
				{
					for (int iRows = 1; iRows <= page.TableRows; iRows++)
					{
						try
						{
							if (!(tAry[iRows - 1, iCols - 1] == null))
							{
								cellInfo = tAry[iRows - 1, iCols - 1];
							}

						}
						catch (Exception)
						{
							continue;
						}

						if (cellInfo != null && !cellInfo.IsEmpty)
						{
							switch (cellInfo.FormControlInfo.Type)
							{
								case ControlType.CheckBox:
								case ControlType.CheckBoxList:
								case ControlType.DropDownList:
								case ControlType.HiddenField:
								case ControlType.RadioButtonList:
								case ControlType.TextBox:
									LIpageField = new HtmlGenericControl("li");
									LIpageField.Attributes.Add("data-value", String.Format("${0}", cellInfo.FormControlInfo.CalcId));
									fieldLabel = String.Format("${0}-{1}", cellInfo.FormControlInfo.CalcId, cellInfo.FormControlInfo.FieldName);
									LIpageField.Attributes.Add("title", fieldLabel);
									LIpageField.InnerText = fieldLabel;
									ULpageFields.Controls.Add(LIpageField);
									break;
							}
						}
					}
				}
				if (ULpageFields.Controls.Count > 0)
				{
					fieldsContainerDiv.Controls.Add(ULpageFields);
					DivClear = new HtmlGenericControl("div");
					DivClear.Attributes.Add("style", "clear:both");
					fieldsContainerDiv.Controls.Add(DivClear);
				}
			}
			this.pnlCalxFields.Controls.Add(fieldsContainerDiv);
		}
		
		//Create the Design Time Form using Table Objects
		private void CreateForm()
		{
			Table oMainTable = new Table();
			Table oFormTable = new Table();
			TableRow oRow = default(TableRow);
			TableCell oLabelCell = null;
			TableCell oControlCell = default(TableCell);
			int iCols = default(int);
			int iRows = default(int);
			Code5Systems.FormMaster.Business.CellInfo oCellInfo = null;
			bool bUseLabelAsControl = default(bool);
			string strMainTblStyle = string.Empty;
			string strFormTblStyle = string.Empty;
			
			Dictionary<string, List<string>> pageScripts = Utility.GetPageScriptsDictionary();
			
			this.phForm.Controls.Clear();
			if (_previewMode)
			{
				if (objFormSettings.ResponsiveLayout)
				{
					objFormCtl.CreateFormRwd(this.ModuleId, this.phForm, true);
				}
				else
				{
					objFormCtl.CreateForm(this.ModuleId, this.phForm, true);
				}
				
				return;
			}
			
			oMainTable.ID = "C5SLLC_MainFormTable";
			
			// we always want to use the style now so make this false
			if (Utility.GetPageDocType(phForm) == Code5Systems.FormMaster.Business.DocType.HTML40 && 1 == 2)
			{
				oMainTable.HorizontalAlign = objFormSettings.TableAlignment;
				if (!string.IsNullOrEmpty(objFormSettings.TableWidth))
				{
					oMainTable.Width = Unit.Parse(objFormSettings.TableWidth);
				}
				
				oFormTable.HorizontalAlign = objFormSettings.FormTableAlignment;
				if (!string.IsNullOrEmpty(objFormSettings.FormTableWidth))
				{
					oFormTable.Width = Unit.Parse(objFormSettings.FormTableWidth);
				}
				if (!string.IsNullOrEmpty(objFormSettings.FormTableHeight))
				{
					oFormTable.Height = Unit.Parse(objFormSettings.FormTableHeight);
				}
			}
			else
			{
				if (!string.IsNullOrEmpty(objFormSettings.TableWidth))
				{
					strMainTblStyle += string.Format("width: {0};", Unit.Parse(objFormSettings.TableWidth).ToString());
				}
				
				switch (objFormSettings.TableAlignment)
				{
					case HorizontalAlign.Left:
						strMainTblStyle += "margin: 0px auto 0px 0px;";
						break;
					case HorizontalAlign.Right:
						strMainTblStyle += "margin: 0px 0px 0px auto;";
						break;
					case HorizontalAlign.Center:
						strMainTblStyle += "margin: 0px auto;";
						break;
				}
				
				if (!string.IsNullOrEmpty(strMainTblStyle))
				{
					oMainTable.Attributes.Add("style", strMainTblStyle);
				}
				
				switch (objFormSettings.FormTableAlignment)
				{
					case HorizontalAlign.Left:
						strFormTblStyle += "margin: 0px auto 0px 0px;";
						break;
					case HorizontalAlign.Right:
						strFormTblStyle += "margin: 0px 0px 0px auto;";
						break;
					case HorizontalAlign.Center:
						strFormTblStyle += "margin: 0px auto;";
						break;
				}
				
				if (!string.IsNullOrEmpty(objFormSettings.FormTableWidth))
				{
					strFormTblStyle += string.Format("width: {0};", Unit.Parse(objFormSettings.FormTableWidth).ToString());
				}
				
				if (!string.IsNullOrEmpty(objFormSettings.FormTableHeight))
				{
					strFormTblStyle += string.Format("height: {0};", Unit.Parse(objFormSettings.FormTableHeight).ToString());
				}
				
				if (!string.IsNullOrEmpty(strFormTblStyle))
				{
					oFormTable.Attributes.Add("style", strFormTblStyle);
				}
				
			}
			
			if (!string.IsNullOrEmpty(objFormInfo.TableClass))
			{
				oMainTable.CssClass = objFormInfo.TableClass;
			}
			
			if (!string.IsNullOrEmpty(objFormSettings.TableClass))
			{
				oFormTable.CssClass = objFormSettings.TableClass;
			}
			
			oRow = new TableRow();
			oControlCell = new TableCell();
			oControlCell.Controls.Add(oFormTable);
			oRow.Cells.Add(oControlCell);
			oMainTable.Rows.Add(oRow);

			if (objFormSettings.UseDefaultFieldFormatting)
			{
				oFormTable.CssClass += " designTimeTable C5SLLC_FormItem";
			}
			else
			{
				oFormTable.CssClass += " designTimeTable";
			}

			oFormTable.CellPadding = 0;
			oFormTable.CellSpacing = 0;
			
			//tAry a two dimensional Array representing Columns x Rows Matrix
			//We will keep information about what is going on in each location
			//usung CellInfo class
			tAry = this.objFormCtl.GetTableMatrix(objFormInfo, objFormInfo.CurrentPage.PageNum);
			
			oRow = new TableRow();
			oControlCell = new TableCell();
			oControlCell.CssClass = "RowColMgrOFF";
			oRow.Cells.Add(oControlCell);
			
			//Set the Collection of Rows and Columns which have fields in them
			usedRows.Clear();
			usedCols.Clear();
			for (iCols = 1; iCols <= objFormInfo.CurrentPage.TableColumns; iCols++)
			{
				for (iRows = 1; iRows <= objFormInfo.CurrentPage.TableRows; iRows++)
				{
					if (!(tAry[iRows - 1, iCols - 1] == null))
					{
						if (!tAry[iRows - 1, iCols - 1].IsEmpty || tAry[iRows - 1, iCols - 1].IsSpanned)
						{
							if (!usedRows.Contains(iRows))
							{
								usedRows.Add(iRows);
							}
							if (!usedCols.Contains(iCols))
							{
								usedCols.Add(iCols);
							}
						}
					}
				}
			}
			
			int delMaxCount = default(int);
			int delMax = default(int);
			for (iCols = 1; iCols <= objFormInfo.CurrentPage.TableColumns; iCols++)
			{
				delMaxCount = 0;
				delMax = 0;
				
				if (IsColmunEmpty(iCols))
				{
					for (delMaxCount = iCols; delMaxCount <= objFormInfo.CurrentPage.TableColumns; delMaxCount++)
					{
						if (IsColmunEmpty(delMaxCount))
						{
							delMax++;
						}
						else
						{
							break;
						}
					}
				}
				
				oControlCell = new TableCell();
				oControlCell.HorizontalAlign = HorizontalAlign.Center;
				oControlCell.VerticalAlign = VerticalAlign.Middle;
				oControlCell.CssClass = "RowColMgrOFF";
				if (this.objFormInfo.CurrentPage.LabelPosition == 2)
				{
					oControlCell.ColumnSpan = 2;
				}
				
				LinkButton lbColMgr = default(LinkButton);
				lbColMgr = new LinkButton();
				lbColMgr.Text = string.Format(Localization.GetString("ColMgr", this.LocalResourceFile), iCols);
				lbColMgr.ID = "cmdColMgr" + "_" + iCols.ToString();
				lbColMgr.CommandName = "ManageColumn";
				lbColMgr.CommandArgument = String.Format("{0},0,{1}", this._curPage, iCols);
				//lbColMgr.CommandArgument = "0," + iCols.ToString();
				lbColMgr.CausesValidation = false;
				lbColMgr.CssClass = "CommandButton";
				lbColMgr.ForeColor = System.Drawing.Color.Black;
				lbColMgr.ToolTip = string.Format(Localization.GetString("ColMgrToolTip", this.LocalResourceFile), iCols);
				lbColMgr.TabIndex = (short) 1000;
				lbColMgr.Font.Bold = true;
				lbColMgr.EnableViewState = false;
				lbColMgr.OnClientClick = string.Format("return jQuery().ShowRowColCont(\'{0}\',\'0\',\'{1}\',\'{2}\',\'{3}\');", _curPage, iCols, 15 - objFormInfo.CurrentPage.TableColumns, delMax);
				
				oControlCell.Attributes.Add("onmouseover", " this.className=\'RowColMgrON\'; ");
				oControlCell.Attributes.Add("onmouseout", " this.className=\'RowColMgrOFF\'; ");
				oControlCell.Controls.Add(lbColMgr);
				
				oRow.Cells.Add(oControlCell);
			}
			
			oFormTable.Rows.Add(oRow);
			
			for (iRows = 1; iRows <= objFormInfo.CurrentPage.TableRows; iRows++)
			{
				delMaxCount = 0;
				delMax = 0;
				
				if (IsRowEmpty(iRows))
				{
					for (delMaxCount = iRows; delMaxCount <= objFormInfo.CurrentPage.TableRows; delMaxCount++)
					{
						if (IsRowEmpty(delMaxCount))
						{
							delMax++;
						}
						else
						{
							break;
						}
					}
				}
				
				oRow = new TableRow();
				oControlCell = new TableCell();
				oControlCell.HorizontalAlign = HorizontalAlign.Center;
				oControlCell.VerticalAlign = VerticalAlign.Middle;
				oControlCell.CssClass = "RowColMgrOFF";
				
				LinkButton lbRowMgr = default(LinkButton);
				lbRowMgr = new LinkButton();
				lbRowMgr.Text = string.Format(Localization.GetString("RowMgr", this.LocalResourceFile), iRows);
				lbRowMgr.ID = "cmdRowMgr" + "_" + iRows.ToString();
				lbRowMgr.CommandName = "ManageRow";
				lbRowMgr.CommandArgument = String.Format("{0},{1},0", iRows, _curPage);
				//lbRowMgr.CommandArgument = iRows.ToString() + ",0";
				lbRowMgr.CausesValidation = false;
				lbRowMgr.CssClass = "CommandButton";
				lbRowMgr.ForeColor = System.Drawing.Color.Black;
				lbRowMgr.ToolTip = string.Format(Localization.GetString("RowMgrToolTip", this.LocalResourceFile), iRows);
				lbRowMgr.TabIndex = (short) 1000;
				lbRowMgr.Font.Bold = true;
				lbRowMgr.EnableViewState = false;
				lbRowMgr.OnClientClick = string.Format("return jQuery().ShowRowColCont(\'{0}\',\'{1}\',\'0\',\'{2}\',\'{3}\');", _curPage, iRows, 200 - objFormInfo.CurrentPage.TableRows, delMax);
				
				oControlCell.Attributes.Add("onmouseover", " this.className=\'RowColMgrON\'; ");
				oControlCell.Attributes.Add("onmouseout", " this.className=\'RowColMgrOFF\'; ");
				oControlCell.Controls.Add(lbRowMgr);
				
				oRow.Cells.Add(oControlCell);
				
				for (iCols = 1; iCols <= objFormInfo.CurrentPage.TableColumns; iCols++)
				{
					bUseLabelAsControl = false;
					
					try
					{
						if (!(tAry[iRows - 1, iCols - 1] == null))
						{
							oCellInfo = tAry[iRows - 1, iCols - 1];
						}
						
					}
					catch (Exception)
					{
						//Do Noting
					}
					
					if (!oCellInfo.IsSpanned)
					{
						
						oControlCell = new TableCell();
						oControlCell.VerticalAlign = VerticalAlign.Top;
						oControlCell.RowSpan = oCellInfo.RowSpan;
						oControlCell.ColumnSpan = oCellInfo.ColSpan;
						
						//Label Position "2" = on the left
						if (this.objFormInfo.CurrentPage.LabelPosition == 2)
						{
							oLabelCell = new TableCell();
							oLabelCell.VerticalAlign = VerticalAlign.Top;
							
							if (oCellInfo.ColSpan > 1)
							{
								oControlCell.ColumnSpan = oCellInfo.ColSpan + 1;
							}
							
							oLabelCell.RowSpan = oCellInfo.RowSpan;
						}
						
						//If this is a Label or Submit Button Colspan gets weird
						//If the Control Lables are set to "2" on the Left
						//Then if the Control Lable is Hidden the ColSpan simply doubles
						//Else the ColSpan doubles minus 1 for the Control Label
						
						if (oCellInfo.FormControlInfo != null)
						{
							if (oCellInfo.FormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.Label || oCellInfo.FormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.SubmitButton)
							{
								if (this.objFormInfo.CurrentPage.LabelPosition == 2)
								{
									if (oCellInfo.FormControlInfo.HideLabel)
									{
										oLabelCell.ColumnSpan = oCellInfo.ColSpan * 2;
										
										//If we are hiding the Control Label put the control in
										//the Label Cell
										bUseLabelAsControl = true;
									}
									else
									{
										oControlCell.ColumnSpan = (oCellInfo.ColSpan * 2) - 1;
									}
									
									
								}
							}
							
							if (oLabelCell != null)
							{
								if (bUseLabelAsControl)
								{
									if (oCellInfo.FormControlInfo.ControlAlign == HorizontalAlign.NotSet)
									{
										oLabelCell.HorizontalAlign = HorizontalAlign.Left;
									}
									else
									{
										oLabelCell.HorizontalAlign = oCellInfo.FormControlInfo.ControlAlign;
									}
								}
								else
								{
									if (oCellInfo.FormControlInfo.LabelAlign == HorizontalAlign.NotSet)
									{
										oLabelCell.HorizontalAlign = oCellInfo.FormControlInfo.LabelAlign;
									}
									else
									{
										oLabelCell.HorizontalAlign = oCellInfo.FormControlInfo.LabelAlign;
									}
								}
							}
							
							if (oCellInfo.FormControlInfo.ControlAlign == HorizontalAlign.NotSet)
							{
								oControlCell.HorizontalAlign = HorizontalAlign.Left;
							}
							else
							{
								oControlCell.HorizontalAlign = oCellInfo.FormControlInfo.ControlAlign;
							}
							
							
						}
						
						if (bUseLabelAsControl)
						{
							AddCellControls(oCellInfo.FormControlInfo, null, oLabelCell, iRows.ToString(), iCols.ToString());
						}
						else
						{
							AddCellControls(oCellInfo.FormControlInfo, oLabelCell, oControlCell, iRows.ToString(), iCols.ToString());
						}
						
						if (oLabelCell != null)
						{
							oRow.Cells.Add(oLabelCell);
						}
						
						if (!bUseLabelAsControl)
						{
							oRow.Cells.Add(oControlCell);
						}
					}
				}
				
				oFormTable.Rows.Add(oRow);
				
			}
			
			//Add the "Also Send me a Copy" checkbox to the form
			if (objFormInfo.ShowCcMe)
			{
				oRow = new TableRow();
				oControlCell = new TableCell();
				
				if (objFormInfo.CurrentPage.LabelPosition == 2)
				{
					oControlCell.ColumnSpan = System.Convert.ToInt32(((objFormInfo.CurrentPage.TableColumns + 1) * 2) - 1);
					oRow.Cells.Add(new TableCell());
				}
				else
				{
					oControlCell.ColumnSpan = objFormInfo.CurrentPage.TableColumns + 1;
				}
				
				CheckBox chkCcMe = new CheckBox();
				chkCcMe.ID = "chkCcMe";
				chkCcMe.CssClass = "SubHead";
				chkCcMe.Text = Localization.GetString("ControlCcMe", this.LocalResourceFile);
				oControlCell.Controls.Add(chkCcMe);
				oRow.Cells.Add(oControlCell);
				oFormTable.Rows.Add(oRow);
				
			}
			
			if (!_hasSubmitButton)
			{
				oRow = new TableRow();
				
				oControlCell = new TableCell();
				oControlCell.ColumnSpan = System.Convert.ToInt32(objFormInfo.CurrentPage.LabelPosition == 2 ? ((objFormInfo.CurrentPage.TableColumns + 1) * 2) : objFormInfo.CurrentPage.TableColumns + 1);
				oControlCell.HorizontalAlign = HorizontalAlign.Center;
				oControlCell.Attributes.Add("style", "padding:5px;");
				
				LinkButton cmdSubmit = new LinkButton();
				cmdSubmit.ID = "cmdDisabledSubmit";
				cmdSubmit.Text = Localization.GetString("cmdSubmit.Text", this.LocalResourceFile);
				cmdSubmit.CssClass = "CommandButton";
				cmdSubmit.Enabled = false;
				
				oControlCell.Controls.Add(cmdSubmit);
				
				oRow.Cells.Add(oControlCell);
				oFormTable.Rows.Add(oRow);
			}
			
			
			
			if (_hasRequredFieldValidators)
			{
				oRow = new TableRow();
				
				oControlCell = new TableCell();
				oControlCell.ColumnSpan = System.Convert.ToInt32(objFormInfo.CurrentPage.LabelPosition == 2 ? ((objFormInfo.CurrentPage.TableColumns + 1) * 2) : objFormInfo.CurrentPage.TableColumns + 1);
				oControlCell.HorizontalAlign = HorizontalAlign.Center;
				oControlCell.VerticalAlign = VerticalAlign.Middle;
				oControlCell.Attributes.Add("style", "padding:5px;");
				
				Label oLabel = new Label();
				oLabel.ID = "lblRequired";
				oLabel.CssClass = "normal";
				oLabel.Text = objFormSettings.RequiredFieldSymbol + Localization.GetString("Required.Text", this.LocalResourceFile);
				
				oControlCell.Controls.Add(oLabel);
				
				oRow.Cells.Add(oControlCell);
				oFormTable.Rows.Add(oRow);
				
			}
			
			this.phForm.Controls.Clear();
			
			this.phForm.Controls.Add(oMainTable);
			
			//Set the Collection of Rows and Columns which have fields in them
			usedRows.Clear();
			usedCols.Clear();
			for (iCols = 1; iCols <= objFormInfo.CurrentPage.TableColumns; iCols++)
			{
				for (iRows = 1; iRows <= objFormInfo.CurrentPage.TableRows; iRows++)
				{
					if (!(tAry[iRows - 1, iCols - 1] == null))
					{
						if (!tAry[iRows - 1, iCols - 1].IsEmpty || tAry[iRows - 1, iCols - 1].IsSpanned)
						{
							if (!usedRows.Contains(iRows))
							{
								usedRows.Add(iRows);
							}
							if (!usedCols.Contains(iCols))
							{
								usedCols.Add(iCols);
							}
						}
					}
				}
			}
			
			ModuleController modCtl = new ModuleController();
			ModuleInfo modInfo = modCtl.GetModule(this.LoaderCtl.ModuleId);
			ModuleControlInfo modCtlInfo = ModuleControlController.GetModuleControlByControlKey("Dispatcher", modInfo.ModuleDefID);
			
			objFormCtl.GeneratePageScripts(phForm, pageScripts, true, modCtlInfo.SupportsPartialRendering);
			
		}
		
		//Add the control to the Design Time Form with the Error Message for any Validators
		private void AddCellControls(Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo, TableCell labelCell, TableCell controlCell, string row, string col)
		{
			Code5Systems.FormMaster.Business.FormControlInfo objValidatorFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			Label oLabelControl = default(Label);
			WebControl oInputControl = default(WebControl);
			BaseValidator oValidatorControl = default(BaseValidator);
			Literal oLiteral = null;
			string strControlClass = default(string);
			string strTdClass = string.Empty;
			
			if (objFormControlInfo != null)
			{
				
				//If the User has used a Semi-Colon in the "Class" field, get that Class Name so
				//we can apply it to the TableCell
				string[] aryCssClass = objFormControlInfo.CssClass.Split(';');
				if (aryCssClass.Length == 2)
				{
					strControlClass = (string) (aryCssClass[0].Trim());
					strTdClass = (string) (aryCssClass[1].Trim());
				}
				else
				{
					strControlClass = objFormControlInfo.CssClass.Trim();
				}
				
				if (!objFormControlInfo.HideLabel)
				{
					if (objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.CheckBox)
					{
						oLabelControl = (Label) (new Label());
						oLabelControl.ID = "lbl_" + objFormControlInfo.ID;
						oLabelControl.CssClass = objFormControlInfo.LabelCssClass;
						if (labelCell == null)
						{
							oLabelControl.Text = objFormControlInfo.Label + (objFormControlInfo.Required ? objFormSettings.RequiredFieldSymbol : "").ToString() + "<br />";
							controlCell.Controls.Add(oLabelControl);
						}
						else
						{
							oLabelControl.Text = objFormControlInfo.Label + (objFormControlInfo.Required ? objFormSettings.RequiredFieldSymbol : "").ToString();
							
							if (strTdClass != string.Empty)
							{
								labelCell.Attributes.Add("class", strTdClass);
							}
							
							labelCell.Controls.Add(oLabelControl);
						}

						switch(objFormControlInfo.LabelAlign)
						{
							case HorizontalAlign.Left:
								oLabelControl.Attributes.Add("style", "text-align:left;display:block");
								break;
							case HorizontalAlign.Center:
								oLabelControl.Attributes.Add("style", "text-align:center;display:block");
								break;
							case HorizontalAlign.Right:
								oLabelControl.Attributes.Add("style", "text-align:right;display:block");
								break;
						}
					}
				}
				
				if (objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.HiddenField)
				{
					oLiteral = new Literal();
					oLiteral.Text = "<div style=\"font-size:10px;padding:5px;width:150px;\" class=\"Normal\">";
					oLiteral.Text += Localization.GetString("HiddenFieldMessage", this.LocalResourceFile);
					oLiteral.Text += "</div>";
					controlCell.Controls.Add(oLiteral);
				}
				
				//The File Upload Control inherits from a different base class than the other WebControls
				//so must be handled separatly
				if (objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.FileUpload)
				{
					oLiteral = new Literal();
					string strFileTypes;
					strFileTypes = "." + objFormControlInfo.FileTypes.Replace(",", " .");
					string strFileSizeFormatMsg = "";
					string strFileTypeFormatMsg = "";
					
					strFileSizeFormatMsg += Localization.GetString("FileSizeFormat.Text", Utility.GetSharedResourceFile());
					strFileSizeFormatMsg = strFileSizeFormatMsg.Replace("[MAXFILESIZE]", objFormControlInfo.MaxFileSize.ToString());
					
					if (!objFormControlInfo.HideFileExtensions)
					{
						strFileTypeFormatMsg += Localization.GetString("FileTypeFormat.Text", Utility.GetSharedResourceFile());
						strFileTypeFormatMsg = strFileTypeFormatMsg.Replace("[FILETYPES]", "." + objFormControlInfo.FileTypes.Replace(",", " ."));
					}
					
					oLiteral.Text = strFileSizeFormatMsg + strFileTypeFormatMsg;
					
					HtmlInputFile objHtmlControl = default(HtmlInputFile);
					objHtmlControl = new HtmlInputFile();
					objHtmlControl.ID = objFormControlInfo.ID;
					objHtmlControl.Disabled = true;

					System.Int32 temp_result = 20;
					if (objFormControlInfo.Width.EndsWith("%"))
					{
						objHtmlControl.Attributes.Add("style", String.Format("width:{0};", objFormControlInfo.Width));
					}
					else if (int.TryParse(objFormControlInfo.Width, out temp_result))
					{
						objHtmlControl.Attributes.Add("style", String.Format("width:{0}px;", temp_result));
					}

					objHtmlControl.Attributes.Add("tabindex", objFormControlInfo.TabIndex);
					
					controlCell.Controls.Add(objHtmlControl);
					
					Label lblFUValMsg = new Label();
					lblFUValMsg.ID = "revType_" + objHtmlControl.ID;
					lblFUValMsg.CssClass = "NormalRed";
					lblFUValMsg.Text = "<br />" + Localization.GetString("FileFormat.ErrorMessage", Utility.GetSharedResourceFile());
					
					controlCell.Controls.Add(oLiteral);
					controlCell.Controls.Add(lblFUValMsg);
					
				}
				else if (objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.HTMLEditor)
				{
					//Dim htmlEditor1 As New DotNetNuke.UI.UserControls.TextEditor
					string strCtl = "<%@ Register TagPrefix=\"dnn\" TagName=\"TextEditor\" Src=\"~/controls/TextEditor.ascx\"%>";
					strCtl += Environment.NewLine;
					strCtl += string.Format("<dnn:texteditor id=\"{0}\" width=\"{1}\" height=\"{2}\" runat=\"server\" />", objFormControlInfo.ID, objFormControlInfo.Width, objFormControlInfo.Height);
					Control htmlEditor = phForm.Page.ParseControl(strCtl);
					controlCell.Controls.Add(htmlEditor);
					
				}
				else if (objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.HiddenField)
				{
					HtmlInputHidden oHiddenField = new HtmlInputHidden();
					oHiddenField.ID = objFormControlInfo.ID;
					oHiddenField.Value = objFormCtl.GetAutoFillValue(objFormControlInfo);
					oHiddenField.Attributes.Add("data-id", objFormControlInfo.CalcId);
					if (!String.IsNullOrWhiteSpace(objFormControlInfo.Formula))
					{
						oHiddenField.Attributes.Add("data-formula", objFormControlInfo.Formula);
					}
					this.phForm.Controls.Add(oHiddenField);
					
				}
				else
				{
					
					oInputControl = (WebControl) (objFormCtl.GetFormControl(objFormControlInfo, true));

					oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
					
					oInputControl.Enabled = objFormControlInfo.Enabled;
					oInputControl.CssClass = strControlClass;
					oInputControl.Width = Unit.Empty;
					
					if (!String.IsNullOrWhiteSpace(objFormControlInfo.Width))
					{
						if (objFormControlInfo.Width.EndsWith("%"))
						{
							oInputControl.Width = Unit.Percentage(double.Parse(objFormControlInfo.Width.Replace("%", "")));
						}
						else
						{
							oInputControl.Width = Unit.Pixel(int.Parse(objFormControlInfo.Width));
						}
					}

					if (objFormControlInfo.Height != string.Empty)
					{
						oInputControl.Height = System.Web.UI.WebControls.Unit.Pixel(int.Parse(objFormControlInfo.Height));
					}
					
					switch (objFormControlInfo.Type)
					{
						
					case Code5Systems.FormMaster.Business.ControlType.Label:
						break;
						//oInputControl.TabIndex = -1
						
					case Code5Systems.FormMaster.Business.ControlType.CheckBox:
						C5CheckBox cBox = oInputControl as C5CheckBox;
						cBox.Checked = objFormControlInfo.Checked;
						cBox.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						cBox.CssClass = objFormControlInfo.CssClass;
						if (objFormControlInfo.HideLabel == false)
						{
							cBox.Text = objFormControlInfo.Label;
							cBox.CssClass += " " + objFormControlInfo.LabelCssClass;
						}
						bool isChecked = default(bool);
						string value = this.objFormCtl.GetAutoFillValue(objFormControlInfo);
						if (!bool.TryParse(value, out isChecked))
						{
							cBox.Attributes.Add("value", value);
						}
						else
						{
							if (!cBox.Checked)
							{
								cBox.Checked = isChecked;
							}
						}
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.CheckBoxList:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						C5CheckBoxList chkCheckBoxList = (C5CheckBoxList) oInputControl;
						chkCheckBoxList.RepeatColumns = int.Parse(objFormControlInfo.RepeatColumns);
						chkCheckBoxList.RepeatDirection = objFormControlInfo.RepeatDirection;
						chkCheckBoxList.CellPadding = 0;
						chkCheckBoxList.CellSpacing = 0;
						chkCheckBoxList.BorderStyle = BorderStyle.None;
						
						try
						{
							objFormCtl.FillControlFromQuery(chkCheckBoxList, objFormControlInfo);
							if (objFormControlInfo.AutoFillType != Code5Systems.FormMaster.Business.FormController.AutoFillType.None)
							{
								string strAutoValue = objFormCtl.GetAutoFillValue(objFormControlInfo);
								chkCheckBoxList.SelectedIndex = chkCheckBoxList.Items.IndexOf(chkCheckBoxList.Items.FindByText(strAutoValue));
							}
						}
						catch (Exception ex)
						{
							DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
						}
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.RadioButtonList:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						C5RadioButtonList rdoCheckBoxList = (C5RadioButtonList) oInputControl;
						rdoCheckBoxList.RepeatColumns = int.Parse(objFormControlInfo.RepeatColumns);
						rdoCheckBoxList.RepeatDirection = objFormControlInfo.RepeatDirection;
						rdoCheckBoxList.CellPadding = 0;
						rdoCheckBoxList.CellSpacing = 0;
						rdoCheckBoxList.BorderStyle = BorderStyle.None;
						
						try
						{
							objFormCtl.FillControlFromQuery(rdoCheckBoxList, objFormControlInfo);
						}
						catch (Exception ex)
						{
							DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
						}
						
						
						if (objFormControlInfo.AutoFillType != Code5Systems.FormMaster.Business.FormController.AutoFillType.None)
						{
							try
							{
								string strAutoValue = objFormCtl.GetAutoFillValue(objFormControlInfo);
								rdoCheckBoxList.SelectedIndex = rdoCheckBoxList.Items.IndexOf(rdoCheckBoxList.Items.FindByText(strAutoValue));
							}
							catch (Exception ex)
							{
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							}
						}
						oInputControl.Attributes.Add("data-c5s", "1");
						oInputControl.Attributes.Add("data-id", objFormControlInfo.CalcId);
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.TextBox:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						if (objFormControlInfo.UseCalendar)
						{
							C5DatePicker picker = new C5DatePicker();
							picker.ID = objFormControlInfo.ID;
							picker.MinDate = DateTime.Now.AddYears(-80);
							DateTime autoFilldate;
							if (DateTime.TryParse(objFormCtl.GetAutoFillValue(objFormControlInfo), out autoFilldate))
							{
								picker.SelectedDate = autoFilldate;
							}
							picker.CssClass = objFormControlInfo.CssClass;
							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Width))
							{
								int width;
								if (int.TryParse(objFormControlInfo.Width, out width))
								{
									picker.Width = Unit.Pixel(width);
								}
							}

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Height))
							{
								int height;
								if (int.TryParse(objFormControlInfo.Height, out height))
								{
									picker.Height = Unit.Pixel(height);
								}
							}

							oInputControl = picker;
							oInputControl.Attributes.Add("type", "date");

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Placeholder))
							{
								oInputControl.Attributes.Add("placeholder", objFormControlInfo.Placeholder);
							}
						}
						else
						{
							if (objFormControlInfo.Columns != string.Empty)
							{
								((TextBox)oInputControl).Columns = int.Parse(objFormControlInfo.Columns);
							}

							if (objFormControlInfo.TextMode == TextBoxMode.MultiLine)
							{

								((TextBox)oInputControl).Wrap = objFormControlInfo.WrapHard;

								if (objFormControlInfo.Rows != string.Empty)
								{
									((TextBox)oInputControl).Rows = int.Parse(objFormControlInfo.Rows);
								}
							}
							try
							{
								((TextBox)oInputControl).Text = objFormCtl.GetAutoFillValue(objFormControlInfo);
							}
							catch (Exception ex)
							{
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							}

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Formula))
							{
								oInputControl.Attributes.Add("data-formula", objFormControlInfo.Formula);
							}

							if (!String.IsNullOrWhiteSpace(objFormControlInfo.Placeholder))
							{
								oInputControl.Attributes.Add("placeholder", objFormControlInfo.Placeholder);
							}
						}
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.ListBox:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						ListBox lstListBox = (ListBox) oInputControl;
						lstListBox.SelectionMode = objFormControlInfo.SelectionMode;
						
						try
						{
							objFormCtl.FillControlFromQuery(lstListBox, objFormControlInfo);
						}
						catch (Exception ex)
						{
							DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
						}
						
						
						if (objFormControlInfo.AutoFillType != Code5Systems.FormMaster.Business.FormController.AutoFillType.None)
						{
							try
							{
								string strAutoValue = objFormCtl.GetAutoFillValue(objFormControlInfo);
								lstListBox.SelectedIndex = lstListBox.Items.IndexOf(lstListBox.Items.FindByText(strAutoValue));
							}
							catch (Exception ex)
							{
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							}
						}
						
						oLiteral = new Literal();
						oLiteral.Text = Localization.GetString("MultiSelect.Text", Utility.GetSharedResourceFile());
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.DropDownList:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						DropDownList lstDropDown = (DropDownList) oInputControl;
						
						if (objFormControlInfo.FillListItemText != string.Empty)
						{
							try
							{
								objFormCtl.FillControlFromQuery(lstDropDown, objFormControlInfo);
								
								
							}
							catch (Exception ex)
							{
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							}
							
						}
						
						if (objFormControlInfo.AutoFillType != Code5Systems.FormMaster.Business.FormController.AutoFillType.None)
						{
							try
							{
								string strAutoValue = objFormCtl.GetAutoFillValue(objFormControlInfo);
								
								if (objFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text)
								{
									lstDropDown.SelectedIndex = lstDropDown.Items.IndexOf(lstDropDown.Items.FindByText(strAutoValue));
								}
								else
								{
									lstDropDown.SelectedIndex = lstDropDown.Items.IndexOf(lstDropDown.Items.FindByValue(strAutoValue));
								}
							}
							catch (Exception ex)
							{
								DotNetNuke.UI.Skins.Skin.AddModuleMessage(_loaderCtl, ex.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
							}
						}
						break;
						
					case Code5Systems.FormMaster.Business.ControlType.SubmitButton:
						oInputControl.TabIndex = short.Parse(objFormControlInfo.TabIndex);
						switch (objFormControlInfo.ButtonType)
						{
							case Code5Systems.FormMaster.Business.ButtonType.Button:
								((Button) oInputControl).Text = objFormControlInfo.Label;
								break;

							case Code5Systems.FormMaster.Business.ButtonType.LinkButton:
								((LinkButton) oInputControl).Text = objFormControlInfo.Label;
								break;

							case Code5Systems.FormMaster.Business.ButtonType.ImageButton:
								FileController oFileCtl = new FileController();
								DotNetNuke.Services.FileSystem.FileInfo oFileInfo = oFileCtl.GetFileById(int.Parse(objFormControlInfo.ButtonImage), PortalId);
								if (oFileInfo != null)
								{
									((ImageButton) oInputControl).ImageUrl = PortalSettings.HomeDirectory + oFileInfo.Folder + oFileInfo.FileName;
								}
								
								((ImageButton) oInputControl).AlternateText = objFormControlInfo.Label;
								break;
								
						}
						
						oInputControl.Enabled = false;
						_hasSubmitButton = true;
						break;
						
				}
				
				controlCell.Controls.Add(oInputControl);
				//if (objFormControlInfo.UseCalendar)
				//{
				//	controlCell.Wrap = false;
				//	System.Web.UI.WebControls.Image oImage = new System.Web.UI.WebControls.Image();
				//	oImage.ID = objFormControlInfo.ID + "img";
				//	oImage.ImageUrl = "~/images/calendar.png";
				//	oImage.AlternateText = Localization.GetString("CalendarToolTip", Utility.GetSharedResourceFile());
				//	controlCell.Controls.Add(oImage);
				//}
				
				if (oLiteral != null)
				{
					controlCell.Controls.Add(oLiteral);
				}
				
			}
			
			if (strTdClass != string.Empty)
			{
				controlCell.Attributes.Add("class", strTdClass);
			}
			
			if (objFormControlInfo.Validators.Count > 0)
			{
				System.Collections.IEnumerator myEnumerator = objFormControlInfo.Validators.GetEnumerator();
				Label lblValMsg = default(Label);
				
				while (myEnumerator.MoveNext())
				{
					lblValMsg = new Label();
					lblValMsg.Attributes.Add("style", "display:block;");
					objValidatorFormControlInfo = (Code5Systems.FormMaster.Business.FormControlInfo) myEnumerator.Current;
					
					oValidatorControl = (BaseValidator) (objFormCtl.GetFormControl(objValidatorFormControlInfo, true));
					lblValMsg.ID = oValidatorControl.ID;
					lblValMsg.CssClass = objFormSettings.UseFormErrorFormatting ? "NormalRed" : oValidatorControl.CssClass;
					lblValMsg.Text = oValidatorControl.Text;
					lblValMsg.Attributes.Add("style", "clear:both;display:block;");
					controlCell.Controls.Add(lblValMsg);
					
					if (objValidatorFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.RequiredFieldValidator)
					{
						_hasRequredFieldValidators = true;
					}
					
				}
				
			}
			
		}
		
		AddCmdButtons(objFormControlInfo, controlCell, int.Parse(row), int.Parse(col));
		
	}
	
	//Add the cell Commmand buttons based on location and content.
	private void AddCmdButtons(Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo, TableCell cell, int row, int col)
	{
		
		if (objFormControlInfo == null)
		{
			//Just add the "Add" command button
			LinkButton lbAdd = default(LinkButton);
			lbAdd = new LinkButton();
			lbAdd.Text = Localization.GetString("CellAdd", this.LocalResourceFile);
			lbAdd.ID = "cmdAdd" + row.ToString() + "_" + col.ToString();
			lbAdd.CommandName = "Add Form Item";
			lbAdd.CommandArgument = String.Format("{0},{1},{2}", objFormInfo.CurrentPage.PageNum, row, col);
			lbAdd.CausesValidation = false;
			lbAdd.CssClass = "CommandButton";
			lbAdd.ToolTip = Localization.GetString("AddFormControl", this.LocalResourceFile);
			lbAdd.TabIndex = (short) 1000;
			lbAdd.Command += new System.Web.UI.WebControls.CommandEventHandler(cmdAdd_Click);
			cell.Controls.Add(lbAdd);
		}
		else
		{
			//Control already exists, need an "Edit" button
			LinkButton lbEdit = default(LinkButton);
			lbEdit = new LinkButton();
			lbEdit.Text = Localization.GetString("CellEdit", this.LocalResourceFile);
			lbEdit.ID = "cmdEdit" + row.ToString() + "_" + col.ToString();
			lbEdit.CommandName = "Edit Form Item";
			lbEdit.CommandArgument = String.Format("{0},{1},{2}", objFormInfo.CurrentPage.PageNum, row, col);
			lbEdit.CausesValidation = false;
			lbEdit.CssClass = "CommandButton";
			lbEdit.ToolTip = Localization.GetString("EditFormControl", this.LocalResourceFile);
			lbEdit.TabIndex = (short) 1000;
			lbEdit.Command += new System.Web.UI.WebControls.CommandEventHandler(cmdEdit_Click);
			cell.Controls.Add(new LiteralControl("<br />"));
			cell.Controls.Add(lbEdit);
			
			//And a Delete button
			LinkButton lbDelete = default(LinkButton);
			lbDelete = new LinkButton();
			lbDelete.Text = Localization.GetString("CellDelete", this.LocalResourceFile);
			lbDelete.ID = "cmdDel" + row.ToString() + "_" + col.ToString();
			lbDelete.CommandName = "Delete Form Item";
			lbDelete.CommandArgument = String.Format("{0},{1},{2}", objFormInfo.CurrentPage.PageNum, row, col);
			lbDelete.CausesValidation = false;
			lbDelete.CssClass = "CommandButton";
			lbDelete.ToolTip = Localization.GetString("DeleteFormControl", this.LocalResourceFile);
			lbDelete.Attributes.Add("onclick", "javascript:return confirm(\'" + Localization.GetString("DeleteItemMessage", LocalResourceFile) + "\');");
			lbDelete.TabIndex = (short) 1000;
			lbDelete.Command += new System.Web.UI.WebControls.CommandEventHandler(cmdDelete_Click);
			cell.Controls.Add(new LiteralControl("&#160;"));
			cell.Controls.Add(lbDelete);
			
			//Add the Move To button
			LinkButton lbMoveTo = new LinkButton();
			lbMoveTo.Text = Localization.GetString("CellMove", this.LocalResourceFile);
			lbMoveTo.ID = "cmdMoveTo" + row.ToString() + "_" + col.ToString();
			lbMoveTo.CommandName = (string) (FormController.MoveDirection.MoveTo.ToString());
			lbMoveTo.CommandArgument = String.Format("{0},{1},{2}", objFormInfo.CurrentPage.PageNum, row, col);
			lbMoveTo.CausesValidation = false;
			lbMoveTo.CssClass = "CommandButton";
			lbMoveTo.ToolTip = Localization.GetString("CellMoveToolTip", this.LocalResourceFile);
			lbMoveTo.TabIndex = (short) 1000;
			lbMoveTo.OnClientClick = String.Format("return jQuery().ShowMoveCopyRowCol('{0},{1},{2}','m')", objFormInfo.CurrentPage.PageNum, row, col);
			//lbMoveTo.OnClientClick = "return jQuery().ShowMoveCopyRowCol(\'" + row.ToString() + "," + col.ToString() + "\',\'m\');";
			cell.Controls.Add(new LiteralControl("&#160;"));
			cell.Controls.Add(lbMoveTo);
			
			// Add the Copy button
			LinkButton lbCopy = new LinkButton();
			lbCopy.Text = Localization.GetString("CellCopy", this.LocalResourceFile);
			lbCopy.ID = "cmdCopyTo" + row.ToString() + "_" + col.ToString();
			lbCopy.CommandName = "CopyTo";
			lbCopy.CommandArgument = String.Format("{0},{1},{2}", objFormInfo.CurrentPage.PageNum, row, col);
			lbCopy.CausesValidation = false;
			lbCopy.CssClass = "CommandButton";
			lbCopy.ToolTip = Localization.GetString("CellCopyToolTip", this.LocalResourceFile);
			lbCopy.TabIndex = (short) 1000;
			lbCopy.OnClientClick = String.Format("return jQuery().ShowMoveCopyRowCol('{0},{1},{2}','c')", objFormInfo.CurrentPage.PageNum, row, col);
			//lbCopy.OnClientClick = "return jQuery().ShowMoveCopyRowCol(\'" + row.ToString() + "," + col.ToString() + "\',\'c\');";
			cell.Controls.Add(new LiteralControl("&#160;"));
			cell.Controls.Add(lbCopy);

			cell.Controls.Add(new LiteralControl("<br />"));

			if (!objFormSettings.ResponsiveLayout)
			{
				//Add the ColSpan Dropdown List
				DropDownList lstColSpan = new DropDownList();
				lstColSpan.ID = "lstColSpan" + row.ToString() + "_" + col.ToString();
				lstColSpan.AutoPostBack = true;
				lstColSpan.CssClass = "tinyDropdown";
				lstColSpan.ToolTip = Localization.GetString("ColSpanToolTip", this.LocalResourceFile);
				lstColSpan.TabIndex = (short) 1000;
			
				for (int i = 1; i <= GetMaxColSpanValue(objFormInfo, objFormControlInfo, row, col); i++)
				{
					lstColSpan.Items.Add(new ListItem(i.ToString(), col.ToString() + ";" + row.ToString() + ";" + i.ToString()));
				}
			
				if (objFormControlInfo != null)
				{
					lstColSpan.SelectedIndex = lstColSpan.Items.IndexOf(lstColSpan.Items.FindByText(objFormControlInfo.ColSpan));
				}
			
				lstColSpan.SelectedIndexChanged += new System.EventHandler(ColSpanHandler);
				cell.Controls.Add(new LiteralControl("<div class=\"divSpan\">" + Localization.GetString("ColSpan", LocalResourceFile) + "&#160;"));
				cell.Controls.Add(lstColSpan);
			}

			if (!objFormSettings.ResponsiveLayout)
			{
				//Add the RowSpan Dropdown List
				DropDownList lstRowSpan = new DropDownList();
				lstRowSpan.ID = "lstRowSpan" + row.ToString() + "_" + col.ToString();
				lstRowSpan.AutoPostBack = true;
				lstRowSpan.CssClass = "tinyDropdown";
				lstRowSpan.ToolTip = Localization.GetString("RowSpanToolTip", this.LocalResourceFile);
				lstRowSpan.TabIndex = (short)1000;

				for (int i = 1; i <= GetMaxRowSpanValue(objFormInfo, objFormControlInfo, row, col); i++)
				{
					lstRowSpan.Items.Add(new ListItem(i.ToString(), col.ToString() + ";" + row.ToString() + ";" + i.ToString()));
				}

				if (objFormControlInfo != null)
				{
					lstRowSpan.SelectedIndex = lstRowSpan.Items.IndexOf(lstRowSpan.Items.FindByText(objFormControlInfo.RowSpan));
				}

				lstRowSpan.SelectedIndexChanged += new System.EventHandler(RowSpanHandler);
				cell.Controls.Add(new LiteralControl("&#160;" + Localization.GetString("RowSpan", LocalResourceFile) + "&#160;"));
				cell.Controls.Add(lstRowSpan);
			}
			
			//Add the TabIndex Dropdown List
			//Label Control TabIndex defaults to 0
			if (objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.Label)
			{
				
				DropDownList lstTabIndex = new DropDownList();
				lstTabIndex.ID = "lstTabIndex" + row.ToString() + "_" + col.ToString();
				lstTabIndex.AutoPostBack = true;
				lstTabIndex.CssClass = "tinyDropdown";
				lstTabIndex.ToolTip = Localization.GetString("TabIndexToolTip", this.LocalResourceFile);
				lstTabIndex.TabIndex = (short) 1000;
				
				for (int i = 1; i <= _controlCount; i++)
				{
					lstTabIndex.Items.Add(new ListItem(i.ToString(), col.ToString() + ";" + row.ToString() + ";" + i.ToString()));
				}
				
				if (objFormControlInfo != null)
				{
					lstTabIndex.SelectedIndex = lstTabIndex.Items.IndexOf(lstTabIndex.Items.FindByText(objFormControlInfo.TabIndex));
				}
				
				lstTabIndex.SelectedIndexChanged += new System.EventHandler(TabIndexHandler);
				cell.Controls.Add(new LiteralControl("&#160;" + Localization.GetString("TabIndex", LocalResourceFile) + "&#160;"));
				cell.Controls.Add(lstTabIndex);
				
				cell.Controls.Add(new LiteralControl("</div>"));
				
			}
		}
		
	}
	
	//Get the Maximum value for the RowSpan Dropdown List for a Cell
	//Exits when a Cell in the Matrix has a Control is is Spanned
	protected int GetMaxRowSpanValue(Code5Systems.FormMaster.Business.FormInfo objFormInfo, Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo, int row, int col)
	{
		int intMaxRowSpan = 1;
		bool bDone = false;
		Code5Systems.FormMaster.Business.CellInfo oThisCellInfo = tAry[row - 1, col - 1];
		
		for (int r = row; r <= objFormInfo.CurrentPage.TableRows - 1; r++)
		{
			for (int c = oThisCellInfo.Col; c <= (oThisCellInfo.Col + oThisCellInfo.ColSpan) - 1; c++)
			{
				Code5Systems.FormMaster.Business.CellInfo oCellInfo = tAry[r, c - 1];
				if (!oCellInfo.IsEmpty || oCellInfo.IsSpanned)
				{
					if (!oThisCellInfo.FormControlInfo.IsEqualTo(oCellInfo.SpanOwner))
					{
						bDone = true;
						break;
					}
				}
			}
			if (!bDone)
			{
				intMaxRowSpan++;
			}
			else
			{
				break;
			}
		}
		
		return intMaxRowSpan;
		
	}
	
	//Get the Maximum value for the ColSpan Dropdown List for a Cell
	//Exits when a Cell in the Matrix has a Control is is Spanned
	protected int GetMaxColSpanValue(Code5Systems.FormMaster.Business.FormInfo objFormInfo, Code5Systems.FormMaster.Business.FormControlInfo objFormControlInfo, int row, int col)
	{
		int intMaxColSpan = 1;
		bool bDone = false;
		Code5Systems.FormMaster.Business.CellInfo oThisCellInfo = tAry[row - 1, col - 1];
		
		for (int c = col; c <= objFormInfo.CurrentPage.TableColumns - 1; c++)
		{
			for (int r = oThisCellInfo.Row; r <= (oThisCellInfo.Row + oThisCellInfo.RowSpan) - 1; r++)
			{
				Code5Systems.FormMaster.Business.CellInfo oCellInfo = tAry[r - 1, c];
				if (!oCellInfo.IsEmpty || oCellInfo.IsSpanned)
				{
					if (!oThisCellInfo.FormControlInfo.IsEqualTo(oCellInfo.SpanOwner))
					{
						bDone = true;
						break;
					}
				}
			}
			if (!bDone)
			{
				intMaxColSpan++;
			}
			else
			{
				break;
			}
		}
		
		return intMaxColSpan;
		
	}
	
	//Bind the Dynamic user created control names to the dropdown list
	//Used when the Send To: and Send From: values are "Use Form Value"
	private void BindDynamicControls(DropDownList oListContol, bool IncludeCheckboxControls = true)
	{
		string valuePart = default(string);
		string textPart = default(string);
		Code5Systems.FormMaster.Business.ControlType oType = default(Code5Systems.FormMaster.Business.ControlType);
		
		if (xDoc.Root.Elements("Controls").Elements("Control").Count() > 0)
		{
			oListContol.Items.Clear();
		}
		
		foreach (XElement xControl in xDoc.Root.Elements("Controls").Elements("Control"))
		{
			oType = Code5Systems.FormMaster.Business.FormController.GetControlType((string) (xControl.Attributes("Type").First().Value));
			if (oType == Code5Systems.FormMaster.Business.ControlType.CheckBox || oType == Code5Systems.FormMaster.Business.ControlType.CheckBoxList)
			{
				if (!IncludeCheckboxControls)
				{
					continue;
				}
			}
			
			valuePart = (string) (xControl.Attributes("ID").First().Value);
			textPart = (string) (xControl.Attributes("FieldName").First().Value);
			
			if (oType != Code5Systems.FormMaster.Business.ControlType.Label)
			{
				oListContol.Items.Add(new ListItem(textPart, valuePart));
			}
		}
		
	}
	
#endregion
	
#region Conrtol Form Data Bind Methods
	
	private void AddInsertAtCursorScript()
	{
		if (File.Exists(Server.MapPath(this.ControlPath + "assets/js/InsertAtCursor.js")))
		{
			if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), this.GetType().ToString()))
			{
				StreamReader iFile = File.OpenText(Server.MapPath(this.ControlPath + "assets/js/InsertAtCursor.js"));
				Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.GetType().ToString(), iFile.ReadToEnd(), false);
				iFile.Close();
			}
			this.cmdInsertQueryToken.OnClientClick = "return C5SLLC_InsertAtCursor(\'" + this.txtFieldQuery.ClientID + "\',\'" + this.lstQueryTokens.ClientID + "\'); ";
		}
		else
		{
			this.cmdInsertQueryToken.Visible = false;
		}
		
	}
	
	private void AddEditStyles()
	{
		if (File.Exists(Server.MapPath(this.ControlPath + "editcss.txt")))
		{
			StreamReader iFile = File.OpenText(Server.MapPath(this.ControlPath + "editcss.txt"));
			string styleContent = iFile.ReadToEnd();
			styleContent = styleContent.Replace("[TEMPLATEPATH]", this.TemplateSourceDirectory);

			HtmlGenericControl plStyle = (HtmlGenericControl)(this.Page.FindControl("StylePlaceholder"));

			if (plStyle != null)
			{
				plStyle.InnerText = styleContent;
			}
			else
			{
				//DNN 7.3.x Breaking change
				PlaceHolder phStyle = (PlaceHolder)(this.Page.FindControl("ClientDependencyHeadCss"));
				if (phStyle != null)
				{
					styleContent = String.Format("<style type=\"text/css\">{0}</style>", styleContent);
					LiteralControl oLiteral = new LiteralControl();
					oLiteral.Text = styleContent;
					phStyle.Controls.Add(oLiteral);
				}
			}
		}
	}
	
	private void BindControlForm()
	{
		
		
		//Get the information on this control in the current working row and column
		_objFormControlInfo = this.GetFormControlInfo((oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());
		
		if (_objFormControlInfo == null)
		{
			_objFormControlInfo = new Code5Systems.FormMaster.Business.FormControlInfo();
		}
		
		this.trQueryResults.Visible = false;
		
		if (_objFormControlInfo != null)
		{
			
			this.chkControlDisabled.Checked = !_objFormControlInfo.Enabled;
			this.txtColumns.Text = _objFormControlInfo.Columns.ToString();
			this.txtCssClass.Text = _objFormControlInfo.CssClass;
			this.txtHeight.Text = _objFormControlInfo.Height;
			this.txtLabelCssClass.Text = _objFormControlInfo.LabelCssClass;
			this.chkChecked.Checked = _objFormControlInfo.Checked;
			this.txtMaxLength.Text = _objFormControlInfo.MaxLength;
			this.lstRepeatColumns.SelectedIndex = this.lstRepeatColumns.Items.IndexOf(this.lstRepeatColumns.Items.FindByValue(_objFormControlInfo.RepeatColumns));
			this.txtPlaceholder.Text = _objFormControlInfo.Placeholder;

			this.lstRepeatDirection.SelectedIndex = this.lstRepeatDirection.Items.IndexOf(this.lstRepeatDirection.Items.FindByValue(
				_objFormControlInfo.RepeatDirection.EnumToInt<RepeatDirection>().ToString()));

			this.chkHideLabel.Checked = _objFormControlInfo.HideLabel;
			this.chkStoreInDB.Checked = _objFormControlInfo.StoreInDB;
			this.chkHideFileExtensions.Checked = _objFormControlInfo.HideFileExtensions;
			this.chkHideMaxSize.Checked = _objFormControlInfo.HideMaxSize;
			this.txtMaxFileSize.Text = _objFormControlInfo.MaxFileSize.ToString();

			this.lstAutoFillType.SelectedIndex = this.lstAutoFillType.Items.IndexOf(this.lstAutoFillType.Items.FindByValue(
				_objFormControlInfo.AutoFillType.EnumToInt<FormController.AutoFillType>().ToString()));
			
			this.lstSendValueBy.SelectedIndex = this.lstSendValueBy.Items.IndexOf(this.lstSendValueBy.Items.FindByValue(
				_objFormControlInfo.SendValueBy.EnumToInt<FormController.SendValueBy>().ToString()));

			this.txtSendValueByName.Text = _objFormControlInfo.SendValueByName;
			this.txtCookieExpires.Text = (_objFormControlInfo.CookieExpires).ToString();
			this.txtFillListItemText.Text = _objFormControlInfo.FillListItemText;
			this.txtFillListItemValue.Text = _objFormControlInfo.FillListItemValue;
			this.chkAttachFile.Checked = _objFormControlInfo.AttachFile;
			this.chkExcludeLink.Checked = _objFormControlInfo.ExcludeLink;
			this.txtARToken.Text = _objFormControlInfo.ARToken;
			this.chkExcludeField.Checked = _objFormControlInfo.ExcludeField;
			this.chkWrapHard.Checked = _objFormControlInfo.WrapHard;
			this.chkUseCalendar.Checked = _objFormControlInfo.UseCalendar;
			this.chkAllowMarkup.Checked = _objFormControlInfo.AllowMarkup;
			this.chkEncryptField.Checked = _objFormControlInfo.EncryptField;
			
			if (_objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.Label)
			{
				this.htmlEditor.Text = _objFormControlInfo.Text;
			}
			
			this.lstButtonType.SelectedIndex = this.lstButtonType.Items.IndexOf(this.lstButtonType.Items.FindByValue(
				_objFormControlInfo.ButtonType.EnumToInt<Business.ButtonType>().ToString()));

			this.lstLabelAlign.SelectedIndex = this.lstLabelAlign.Items.IndexOf(this.lstLabelAlign.Items.FindByValue(
				_objFormControlInfo.LabelAlign.EnumToInt<HorizontalAlign>().ToString()));

			this.lstControlAlign.SelectedIndex = this.lstControlAlign.Items.IndexOf(this.lstControlAlign.Items.FindByValue(
				_objFormControlInfo.ControlAlign.EnumToInt<HorizontalAlign>().ToString()));

			this.lstListItemToSave.SelectedIndex = this.lstListItemToSave.Items.IndexOf(this.lstListItemToSave.Items.FindByValue(
				_objFormControlInfo.ListItemToSave.EnumToInt<FormController.ListItemToSave>().ToString()));

			this.txtConnection.Text = _objFormControlInfo.ConnectionString;
			this.txtFieldQuery.Text = _objFormControlInfo.FieldQuery;
			this.txtCascadingFieldQuery.Text = _objFormControlInfo.CascadingFieldQuery;
			this.trCascadingQuery.Visible = _objFormControlInfo.IsChildList;
			
			this.lstCascadeParent.DataSource = this.GetAvailableParentListControls(_objFormControlInfo);
			this.lstCascadeParent.DataBind();
			
			this.chkCascadingList.Checked = _objFormControlInfo.CascadingList;
			this.lstCascadeParent.SelectedIndex = this.lstCascadeParent.Items.IndexOf(this.lstCascadeParent.Items.FindByValue(_objFormControlInfo.ParentControlID));
			this.txtPromptText.Text = _objFormControlInfo.PromptText;
			this.txtNotFoundText.Text = _objFormControlInfo.NotFoundText;
			this.txtSelectText.Text = _objFormControlInfo.SelectText;
			this.lblCascadeParent.Visible = this.chkCascadingList.Checked;
			this.lstCascadeParent.Visible = this.chkCascadingList.Checked;
			this.lblPromptText.Visible = this.chkCascadingList.Checked;
			this.txtPromptText.Visible = this.chkCascadingList.Checked;
			this.lblNotFoundText.Visible = this.chkCascadingList.Checked;
			this.txtNotFoundText.Visible = this.chkCascadingList.Checked;
			this.lblSelectText.Visible = this.chkCascadingList.Checked;
			this.txtSelectText.Visible = this.chkCascadingList.Checked;
			this.rfvCascadeParent.Enabled = this.chkCascadingList.Checked;
			this.rfvPromptText.Enabled = this.chkCascadingList.Checked;
			this.rfvNotFoundText.Enabled = this.chkCascadingList.Checked;
			this.rfvSelectText.Enabled = this.chkCascadingList.Checked;
			this.dgListItems.Columns[0].Visible = this.chkCascadingList.Checked;
			this.chkShowOnOwnRow.Checked = _objFormControlInfo.ShowOnOwnRow;
			this.txtFormula.Text = _objFormControlInfo.Formula;
			
			if (bFormChange)
			{
				_objFormControlInfo.Label = this.txtLabel.Text;
				_objFormControlInfo.FieldName = this.txtFieldName.Text;
				_objFormControlInfo.TextMode = (TextBoxMode) (byte.Parse(this.lstTextMode.SelectedValue));
				_objFormControlInfo.Type = (Code5Systems.FormMaster.Business.ControlType) (byte.Parse(lstType.SelectedValue));
				objFormCtl.UpdateTempControlValues(this.xDoc, _objFormControlInfo);
			}
			else
			{
				this.txtLabel.Text = _objFormControlInfo.Label;
				this.txtFieldName.Text = _objFormControlInfo.FieldName;
				
				this.lstTextMode.SelectedIndex = this.lstTextMode.Items.IndexOf(this.lstTextMode.Items.FindByValue(
					_objFormControlInfo.TextMode.EnumToInt<TextBoxMode>().ToString()));

				this.lstType.SelectedIndex = this.lstType.Items.IndexOf(this.lstType.Items.FindByValue(
					_objFormControlInfo.Type.EnumToInt<ControlType>().ToString()));
			}
			
			this.txtRows.Text = _objFormControlInfo.Rows.ToString();
			
			Localization.LocalizeDataGrid(ref dgListItems, LocalResourceFile);
			
			if (_objFormControlInfo.ListItems.Count > 0)
			{
				//If there are list items then just Bind them
				this.dgListItems.DataSource = _objFormControlInfo.ListItems;
				this.dgListItems.DataBind();
			}
			else if (_objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.DropDownList || _objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.CheckBoxList || _objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.RadioButtonList || _objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.ListBox)
			{
				//If there are no list items we must create a ListItem in the Collection
				//then remove it and bind the grid so It will show.
				List<Code5Systems.FormMaster.Business.FMListItem> items = _objFormControlInfo.ListItems;
				items.Add(new Code5Systems.FormMaster.Business.FMListItem());
				items.Clear();
				this.dgListItems.DataSource = items;
				this.dgListItems.DataBind();
			}
			
			this.txtWidth.Text = _objFormControlInfo.Width;
			
			Code5Systems.FormMaster.Business.FormControlInfo objValidatorControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			
			if (_objFormControlInfo.Validators.Count == 0)
			{
				//If there are no Validators we must create a Validator in the Collection
				//then remove it and bind the grid so It will show.
				objValidatorControlInfo = new Code5Systems.FormMaster.Business.FormControlInfo();
				_objFormControlInfo.Validators.Add(objValidatorControlInfo);
				_objFormControlInfo.Validators.Clear();
			}
			
			Localization.LocalizeDataGrid(ref dgValidators, LocalResourceFile);
			
			this.dgValidators.DataSource = _objFormControlInfo.Validators;
			this.dgValidators.DataBind();
			
			//Determine which Form Elements we need to show
			SetFields(_objFormControlInfo);
			
		}
		
		if ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.ListItems) > 0)
		{
			string curCountry = "";
			if (this.lstCountries.SelectedIndex > -1)
			{
				curCountry = this.lstCountries.SelectedValue;
			}
			ListController ctlEntry = new ListController();
			ListEntryInfoCollection entryCollection = ctlEntry.GetListEntryInfoCollection("Country");
			this.lstCountries.DataSource = entryCollection;
			this.lstCountries.DataBind();
			
			this.lstCountries.SelectedIndex = this.lstCountries.Items.IndexOf(this.lstCountries.Items.FindByValue(curCountry));
			
		}
		
		//Set the Visible Status of the Table Rows using a Bitwise AND operator
		this.pnlDesign.Visible = false;
		this.pnlField.Visible = true;
		this.trButtonImage.Visible = false;
		this.imgButton.Visible = true;
		this.trChecked.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.Checked) > 0) ? true : false;
		//this.trColumns.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.Columns) > 0) ? true : false;
		
		this.trListItems.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.ListItems) > 0) ? true : false;
		this.trListOptions.Visible = this.trListItems.Visible;
		this.trAutoFillStates.Visible = this.trListItems.Visible;
		this.trAutoFillCountries.Visible = this.trListItems.Visible;
		this.trAutoFillDisplayValue.Visible = this.trListItems.Visible;
		if (_objFormControlInfo.Type == Code5Systems.FormMaster.Business.ControlType.DropDownList)
		{
			this.trCascadingDropdown.Visible = true;
			this.trCascadingDropdown2.Visible = true;
			if (_objFormControlInfo.IsParentList)
			{
				this.lblCascadingParentMsg.Text = string.Format(Localization.GetString("CascadingListParent", this.LocalResourceFile), _objFormControlInfo.ChildControlName);
				this.lblCascadingParentMsg.Visible = true;
			}
		}
		else
		{
			this.trCascadingDropdown.Visible = false;
			this.trCascadingDropdown2.Visible = false;
		}

		//this.trListItems.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.RepeatColumns) > 0) ? true : false;
		this.trRepeatColumns.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.RepeatColumns) > 0) ? true : false;
		this.trRepeatDirection.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.RepeatDirection) > 0) ? true : false;
		//this.trTextMode.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.TextMode) > 0) ? true : false;
		//this.trTextBox.Visible = this.trTextMode.Visible;
		this.trValidators.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.Validators) > 0) ? true : false;
		this.trHtmlEditor.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.HtmlEditor) > 0) ? true : false;
		
		this.trAutoFill.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField) > 0) ? true : false;
		this.trAutoFillFrom.Visible = this.trAutoFill.Visible;
		this.trAutoFillParam.Visible = this.trAutoFill.Visible;
		
		if (_objFormControlInfo.AutoFillType == Code5Systems.FormMaster.Business.FormController.AutoFillType.Membership)
		{
			this.lstAutoFillFieldFrom.Visible = true;
			this.lstServerVariables.Visible = false;
		}
		else if (_objFormControlInfo.AutoFillType == Code5Systems.FormMaster.Business.FormController.AutoFillType.ServerVariables)
		{
			this.lstAutoFillFieldFrom.Visible = false;
			this.lstServerVariables.Visible = true;
		}

		this.autoFillOptions.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.AutoFillField) > 0) ? true : false;
		//this.dshTextBoxOptions.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.TextBox) > 0) ? true : false;
		this.dshQueryOptions.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.FieldQuery) > 0) ? true : false;
		//this.dshSendValue.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy) > 0) ? true : false;

		this.tblTextBoxOptions.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.TextBox) > 0) ? true : false;
		//this.tblQueryOptions.Visible = this.dshQueryOptions.Visible;
		this.tblSendByOptions.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.SendValueBy) > 0) ? true : false;
		
		this.trListTextValuePair.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.FillListItem) > 0) ? true : false;

		this.uploadSettings.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.FileUpload) > 0) ? true : false;
		this.lblUploadTypeWizardMsg.Visible = objFormCtl.Pages.Count > 1;
		this.trSubmitButton.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.SubmitButton) > 0) ? true : false;
		this.trListItemToSave.Visible = ((editFields & Code5Systems.FormMaster.Business.FormController.Fields.ListItems) > 0) ? true : false;
		
		if (this.trDefaultText.Visible)
		{
			if (_objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.Label)
			{
				this.txtDefaultText.Text = _objFormControlInfo.Text;
			}
		}

		if (_objFormControlInfo.Type == ControlType.TextBox || _objFormControlInfo.Type == ControlType.HiddenField)
		{
			this.trFormula.Visible = true;
			CreateCalxWizard();
		}
		else
		{
			this.trFormula.Visible = false;
		}
		
		ProfilePropertyDefinitionCollection properties = objFormCtl.GetProfileProperties();
		
		this.lstAutoFillFieldFrom.Items.Clear();
		this.lstQueryTokens.Items.Clear();
		foreach (ProfilePropertyDefinition profProperty in properties)
		{
			this.lstAutoFillFieldFrom.Items.Add(new ListItem(profProperty.PropertyCategory + ": " + profProperty.PropertyName, profProperty.PropertyName));
			this.lstQueryTokens.Items.Add(new ListItem(profProperty.PropertyCategory + ": " + profProperty.PropertyName, "#" + profProperty.PropertyName + "#"));
		}
		
		this.lstAutoFillFieldFrom.Items.Add(new ListItem(Localization.GetString("UserID", Utility.GetSharedResourceFile()), "UserID"));
		this.lstAutoFillFieldFrom.Items.Add(new ListItem(Localization.GetString("UserName", Utility.GetSharedResourceFile()), "UserName"));
		this.lstAutoFillFieldFrom.Items.Add(new ListItem(Localization.GetString("FullName", Utility.GetSharedResourceFile()), "FullName"));
		this.lstAutoFillFieldFrom.Items.Add(new ListItem(Localization.GetString("DisplayName", Utility.GetSharedResourceFile()), "DisplayName"));
		
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("UserID", Utility.GetSharedResourceFile()), "#UserID#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("UserName", Utility.GetSharedResourceFile()), "#UserName#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("FullName", Utility.GetSharedResourceFile()), "#FullName#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("DisplayName", Utility.GetSharedResourceFile()), "#DisplayName#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("URLToken", Utility.GetSharedResourceFile()), "#URL:YOURURLPARAMNAME#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("SessionToken", Utility.GetSharedResourceFile()), "#SESSION:YOURSESSIONPARAMNAME#"));
		this.lstQueryTokens.Items.Add(new ListItem(Localization.GetString("CascadeToken", Utility.GetSharedResourceFile()), "#CASCADE:DO_NOT_EDIT#"));
		
		this.lstAutoFillFieldFrom.Items.Insert(0, new ListItem("<< Select >>", "0"));
		this.lstAutoFillFieldFrom.SelectedIndex = this.lstAutoFillFieldFrom.Items.IndexOf(this.lstAutoFillFieldFrom.Items.FindByValue(_objFormControlInfo.AutoFillFrom));

		if (this.lstServerVariables.Items.FindByValue("0") == null)
		{
			this.lstServerVariables.Items.Insert(0, new ListItem("<< Select >>", "0"));
		}
		this.lstServerVariables.SelectedIndex = this.lstServerVariables.Items.IndexOf(this.lstServerVariables.Items.FindByValue(_objFormControlInfo.AutoFillFrom));
		
		if (this.trAutoFill.Visible)
		{
			switch (_objFormControlInfo.AutoFillType)
			{
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.None:
					this.trAutoFillFrom.Visible = false;
					this.trAutoFillParam.Visible = false;
					this.trDefaultText.Visible = true;
					break;
					
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.Membership:
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.ServerVariables:
					this.trAutoFillFrom.Visible = true;
					this.trAutoFillParam.Visible = false;
					this.trDefaultText.Visible = false;
					break;
					
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.Session:
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.Url:
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.Cookie:
					this.trAutoFillFrom.Visible = false;
					this.trAutoFillParam.Visible = true;
					this.trDefaultText.Visible = false;
					this.txtAutoFillFieldParam.Text = _objFormControlInfo.AutoFillFrom;
					break;
					
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.FormQuery:
					this.trAutoFillFrom.Visible = false;
					this.trAutoFillParam.Visible = true;
					this.trDefaultText.Visible = false;
					this.txtAutoFillFieldParam.Text = _objFormControlInfo.AutoFillFrom;
					break;
					
				case Code5Systems.FormMaster.Business.FormController.AutoFillType.FieldQuery:
					this.trAutoFillFrom.Visible = false;
					this.trAutoFillParam.Visible = true;
					this.trDefaultText.Visible = false;
					this.txtAutoFillFieldParam.Text = _objFormControlInfo.AutoFillFrom;
					break;
					
					
			}
			
			if (this.trDefaultText.Visible)
			{
				
				//We set the visibility status above but the ControlType has the last say
				//If it is not a TextBox then we cannot use Default Text
				if (_objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.TextBox 
					&& _objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.HiddenField
					&& _objFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.CheckBox)
				{
					this.trDefaultText.Visible = false;
				}
			}
			
		}

		if (uploadSettings.Visible)
		{
			string[] aryFileExt = null;
			try
			{
				aryFileExt = System.Convert.ToString(DotNetNuke.Entities.Controllers.HostController.Instance.GetSettingsDictionary()["FileExtensions"]).Split(',');
			}
			catch
			{
				string strFileExtensions = "swf,jpg,jpeg,jpe,gif,bmp,png,doc,xls,ppt,pdf,txt,xml,xsl,css,zip,ico";
				aryFileExt = strFileExtensions.Split(',');
			}
			
			ListItem item = default(ListItem);
			this.chkLstFileTypes.Items.Clear();
			for (int i = 0; i <= aryFileExt.Length - 1; i++)
			{
				item = new ListItem(aryFileExt[i]);
				
				if (_objFormControlInfo.FileTypes.IndexOf(aryFileExt[i]) > -1)
				{
					item.Selected = true;
				}
				
				this.chkLstFileTypes.Items.Add(item);
				
			}
		}
		
		if (this.trSubmitButton.Visible)
		{
			if (int.Parse(this.lstButtonType.SelectedValue).ToEnum<Code5Systems.FormMaster.Business.ButtonType>() == Code5Systems.FormMaster.Business.ButtonType.ImageButton)
			{
				this.trButtonImage.Visible = true;
				
				if (_objFormControlInfo.ButtonImage != string.Empty)
				{
					
					FileController oFileCtl = new FileController();
					DotNetNuke.Services.FileSystem.FileInfo oFileInfo = oFileCtl.GetFileById(int.Parse(_objFormControlInfo.ButtonImage), PortalId);
					if (oFileInfo != null)
					{
						this.imgButton.ImageUrl = PortalSettings.HomeDirectory + oFileInfo.Folder + oFileInfo.FileName;
						this.imgButton.AlternateText = _objFormControlInfo.Label;
						this.imgButton.Visible = true;
						
						this.lblCurrentFile.Text = Localization.GetString("CurrentFile.Text", this.LocalResourceFile);
						this.lblCurrentFile.Text += oFileInfo.Folder + oFileInfo.FileName;
					}
					
				}
			}
		}
		
		if (!canEditQuery)
		{
			this.dshQueryOptions.Visible = false;
			//this.tblQueryOptions.Visible = false;
		}
		
	}
	
	//Fills a Form Control ListItem with Regions based on the selected Country
	protected void cmdFillStates_Click(System.Object sender, System.EventArgs e)
	{
		ListEntryInfoCollection aryStates = default(ListEntryInfoCollection);
		ListEntryInfo oStatesInfo = default(ListEntryInfo);
		ControlType controlType = ControlType.DropDownList;
		
		if (Page.IsValid)
		{
			_objFormControlInfo = this.GetFormControlInfo((oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());
			
			if (_objFormControlInfo == null)
			{
				switch (lstType.SelectedItem.Value)
				{
					case "2":
						controlType = Business.ControlType.DropDownList;
						break;
					case "5":
						controlType = Business.ControlType.RadioButtonList;
						break;
					case "4":
						controlType = Business.ControlType.CheckBoxList;
						break;
					case "8":
						controlType = Business.ControlType.ListBox;
						break;
				}

				_objFormControlInfo = objFormCtl.AddControl(this.xDoc, controlType, (oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());
				FillFormControlInfo(_objFormControlInfo);
				objFormCtl.UpdateControlValues(this.xDoc, _objFormControlInfo);
				SaveFormDefinition();
			}
			
			if (_objFormControlInfo != null)
			{
				
				ListController ctlEntry = new ListController();
				
				string listKey = "Country." + this.lstCountries.SelectedValue;
				aryStates = ctlEntry.GetListEntryInfoCollection("Region", listKey);
				
				System.Collections.IEnumerator myEnumerator = default(System.Collections.IEnumerator);
				myEnumerator = aryStates.GetEnumerator();
				while (myEnumerator.MoveNext())
				{
					oStatesInfo = (ListEntryInfo) myEnumerator.Current;
					if (this.lstAutoFillDisplayValue.SelectedValue == "1")
					{
						objFormCtl.AddListItem(this.xDoc, _objFormControlInfo, listKey, oStatesInfo.Value, oStatesInfo.Value, false);
					}
					else
					{
						objFormCtl.AddListItem(this.xDoc, _objFormControlInfo, listKey, oStatesInfo.Text, oStatesInfo.Value, false);
					}
				}
				
				SaveFormDefinition();
				
				this.dgListItems.DataSource = _objFormControlInfo.ListItems;
				this.dgListItems.DataBind();
			}
			else
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("ListItemFill.ErrorMessage", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
		}
	}
	
	//Fills a Form Control ListItem with Countries
	protected void cmdFillCountries_Click(System.Object sender, System.EventArgs e)
	{
		ListEntryInfoCollection aryCountries = default(ListEntryInfoCollection);
		ListEntryInfo oCountryInfo = default(ListEntryInfo);
		ControlType controlType = ControlType.DropDownList;
		
		if (Page.IsValid)
		{
			this._objFormControlInfo = this.GetFormControlInfo((oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());

			if (this._objFormControlInfo == null)
			{
				switch(lstType.SelectedItem.Value)
				{
					case "2":
						controlType = Business.ControlType.DropDownList;
						break;
					case "5":
						controlType = Business.ControlType.RadioButtonList;
						break;
					case "4":
						controlType = Business.ControlType.CheckBoxList;
						break;
					case "8":
						controlType = Business.ControlType.ListBox;
						break;
				}
				this._objFormControlInfo = objFormCtl.AddControl(this.xDoc, controlType, (oCtlLoc.Row).ToString(), (oCtlLoc.Col).ToString());
				FillFormControlInfo(this._objFormControlInfo);
				objFormCtl.UpdateControlValues(this.xDoc, this._objFormControlInfo);
				SaveFormDefinition();
			}

			if (this._objFormControlInfo != null)
			{
				
				ListController ctlEntry = new ListController();
				
				aryCountries = ctlEntry.GetListEntryInfoCollection("Country");
				System.Collections.IEnumerator myEnumerator = default(System.Collections.IEnumerator);
				myEnumerator = aryCountries.GetEnumerator();
				while (myEnumerator.MoveNext())
				{
					oCountryInfo = (ListEntryInfo) myEnumerator.Current;
					if (this.lstAutoFillDisplayValue.SelectedValue == "1")
					{
						objFormCtl.AddListItem(this.xDoc, this._objFormControlInfo, string.Empty, oCountryInfo.Value, oCountryInfo.Value, false);
					}
					else
					{
						objFormCtl.AddListItem(this.xDoc, this._objFormControlInfo, string.Empty, oCountryInfo.Text, oCountryInfo.Value, false);
					}
					
				}
				
				SaveFormDefinition();

				this.dgListItems.DataSource = this._objFormControlInfo.ListItems;
				this.dgListItems.DataBind();
			}
			else
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, Localization.GetString("ListItemFill.ErrorMessage", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
		}
	}
	
#endregion
	
	
}
}

